import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import TherapistDashboard from '../views/TherapistDashboard.vue';
import ParentDashboard from '../views/ParentDashboard.vue';
import Home from '../views/Home.vue';
import { useUserStore } from '../store/user';

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
    },
    {
        path: '/register',
        name: 'Register',
        component: Register,
    },
    {
        path: '/therapist/dashboard',
        name: 'TherapistDashboard',
        component: TherapistDashboard,
        meta: { requiresAuth: true, role: 'therapist' },
    },
    {
        path: '/parent/dashboard',
        name: 'ParentDashboard',
        component: ParentDashboard,
        meta: { requiresAuth: true, role: 'parent' },
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, from, next) => {
    const userStore = useUserStore();
    const isLoggedIn = !!userStore.token;

    if (to.meta.requiresAuth && !isLoggedIn) {
        next({ name: 'Login' });
    } else if (to.meta.requiresAuth && to.meta.role && to.meta.role !== userStore.userType) {
        // 如果用户角色不匹配，可以跳转到无权限页面或首页
        next({ name: 'Home' });
    } else {
        next();
    }
});

export default router;